package com.jt.SecurityMain;

import com.alibaba.fastjson.JSON;
import com.jt.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 定义全局异常处理，实现授权失败接口AAccessDeniedHandler
 *
 * */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        try{
            Result result=new Result(402,null,"用户授权失败,请查看用户是否具访问资源有权限");
            String JSONString = JSON.toJSONString(result);
            response.setStatus(200);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().print(JSONString);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.toString());
        }
    }
}
